#include "serialform.h"
#include "ui_serialform.h"
#include <QMessageBox>
#include <QDebug>
#include <QTextCodec>
#include <QTime>

static char recvbuf[2048];
static bool noFinsh;
static int recvFlag;

SerialForm::SerialForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SerialForm)
{
    ui->setupUi(this);

    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
    // ui->label_7->setStyleSheet("QLabel{border-radius:12px;}");

    QPixmap imgOrigin("://images/origin.png"); // 实例化一个img

    ui->label_7->setPixmap(imgOrigin); // 在label中添加img
    ui->label_7->resize(imgOrigin.width(),imgOrigin.height());  // 使用图片尺寸设置label大小

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->comboBox->addItem(info.portName());
    }

    pserialport = new QSerialPort;
    connect(pserialport,SIGNAL(error(QSerialPort::SerialPortError)),
            this,SLOT(handleSerialError(QSerialPort::SerialPortError)));

    connect(ui->pushButton_con, SIGNAL(clicked()), this, SLOT(handle_connect_serial()));
    connect(ui->pushButton_discon, SIGNAL(clicked()), this, SLOT(handle_disconnect_serial()));
    connect(ui->pushButton_send, SIGNAL(clicked()), this, SLOT(handle_send_serial()));
    connect(ui->pushButton_clear, SIGNAL(clicked()), this, SLOT(handle_clear_serial()));
    connect(pserialport, SIGNAL(readyRead()), this, SLOT(hand_recv_serial()));



    ptimer = new QTimer;
    connect(ptimer, SIGNAL(timeout()), this, SLOT(handle_recv_finsh()));

}

SerialForm::~SerialForm()
{
    delete ui;
}

void SerialForm::handle_connect_serial()
{
    pserialport->setPortName(ui->comboBox->currentText());

    //打开串口
    if (pserialport->open(QIODevice::ReadWrite)) {

        pserialport->setDataTerminalReady(true);

        //设置波特率
        pserialport->setBaudRate(QSerialPort::Baud115200);
        //设置数据位数
        pserialport->setDataBits(QSerialPort::Data8);
        //        switch(comDataBits)
        //        {
        //        case 8:  break;
        //        case 7: pserialport->setDataBits(QSerialPort::Data7); break;
        //        case 6: pserialport->setDataBits(QSerialPort::Data6); break;
        //        case 5: pserialport->setDataBits(QSerialPort::Data5); break;
        //        default: break;
        //        }

        //设置奇偶校验
        //设置奇偶校验
        //        switch(comParity)
        //        {
        //        case 0: serial->setParity(QSerialPort::NoParity); break;
        //        default: break;
        //        }
        pserialport->setParity(QSerialPort::NoParity);
        //设置停止位
        pserialport->setStopBits(QSerialPort::OneStop);
        //        switch(comStopBits)
        //        {
        //        case 1: pserialport->setStopBits(QSerialPort::OneStop); break;
        //        case 2: pserialport->setStopBits(QSerialPort::TwoStop); break;
        //        default: break;
        //        }

        //设置流控制
        pserialport->setFlowControl(QSerialPort::NoFlowControl);
        qDebug()<<"open success";

        QPixmap imgBlue("://images/blueled.png"); // 实例化一个img
        ui->label_7->setPixmap(imgBlue); // 在label中添加img
        ui->label_7->resize(imgBlue.width(),imgBlue.height());  // 使用图片尺寸设置label大小

        ui->comboBox->setEnabled(false);


        connect(ui->pushButton_discon, SIGNAL(clicked()), this, SLOT(handle_disconnect_serial()));
        disconnect(ui->pushButton_con, SIGNAL(clicked()), this, SLOT(handle_connect_serial()));


    }
    else
    {
        QMessageBox::warning(this, tr("Error"), tr("端口不存在或被占用"), QMessageBox::Yes);
    }


}
void SerialForm::handle_disconnect_serial()
{
    pserialport->clear();
    pserialport->close();

    disconnect(ui->pushButton_discon, SIGNAL(clicked()), this, SLOT(handle_disconnect_serial()));
    connect(ui->pushButton_con, SIGNAL(clicked()), this, SLOT(handle_connect_serial()));

    QPixmap imgOrigin("://images/origin.png"); // 实例化一个img
    ui->label_7->setPixmap(imgOrigin); // 在label中添加img
    ui->label_7->resize(imgOrigin.width(),imgOrigin.height());  // 使用图片尺寸设置label大小

    ui->comboBox->setEnabled(true);

}
void SerialForm::handle_send_serial()
{
    STR_SERIAL_SND_DATA  snd_data;

    QStringList dstIplist = ui->lineEdit_dstIP->text().split(".");

    if(ui->checkBox_broadcast->isChecked())
    {
        for(int i=0; i<4; i++)
            snd_data.u8DstIpAddr[i] = 0xff;
    }
    else
    {
        if(dstIplist.size() == 4)
        {

            for(int i=0; i<4; i++)
                snd_data.u8DstIpAddr[i] = (quint8)dstIplist[i].toInt();
        }
        else
        {
            QMessageBox::warning(this, tr("Error"), tr("请正确输入IP地址"), QMessageBox::Yes);
            return;
        }
    }

    if(ui->checkBox_hex_send->isChecked())
    {

        QStringList snd_msg = ui->textEdit_send->toPlainText().simplified().split(" ");

        bool ok;
        char num;
        int j = 0;
        for(int i=0; i<snd_msg.size(); i++)
        {
            num = (char)snd_msg[i].toInt(&ok, 16);

            if(ok == true)
            {
                snd_data.u8MsgData[j] = num;
                j++;
            }
            else
                return;

        }
        snd_data.u16MsgLen = j;
        pserialport->write((char*)&snd_data, snd_data.u16MsgLen + sizeof(quint8) *4 + sizeof(quint16));
    }
    else
    {
        snd_data.u16MsgLen = ui->textEdit_send->toPlainText().length();

        QByteArray ba = ui->textEdit_send->toPlainText().toLatin1();

        memcpy(snd_data.u8MsgData, ba.data(), snd_data.u16MsgLen);
        pserialport->write((char*)&snd_data, snd_data.u16MsgLen + sizeof(quint8) *4 + sizeof(quint16));
    }






}
void SerialForm::handle_clear_serial()
{
    ui->textEdit_recv->clear();

}
void SerialForm::hand_recv_serial()
{
    QByteArray buf;
    buf = pserialport->readAll();

    qDebug()<<buf;
    return;


    memcpy(recvbuf+recvFlag, buf.data(), buf.size());
    recvFlag += buf.size();

    if(ptimer->isActive())
        ptimer->stop();

    ptimer->start(20);

    /*
    unsigned char *p = (unsigned char *)buf.data();

    ushort len = *(p+4) | *(p+5)<<4;

    if(len != buf.size()-6)   //一次没接收完
    {

        memcpy(recvbuf+recvFlag, buf.data(), buf.size());
        recvFlag = buf.size();
        noFinsh = true;

        return;
    }




    QString srcIP = QString("%1.%2.%3.%4").arg((uint)(*p)).arg((uint)(*(p+1))).arg((uint)(*(p+2))).arg((uint)(*(p+3)));
    ui->lineEdit_srcIP->setText(srcIP);

*/




}

void SerialForm::handle_recv_finsh()
{


    ptimer->stop();

    QTime time(QTime::currentTime());
    QString currtime = time.toString("hh:mm:ss.zzz");
    ui->textEdit_recv->append(currtime);

    ui->textEdit_recv->insertPlainText(tr(":\r\n"));



    if( (recvFlag != 0)&&(recvFlag > 6) )
    {



        unsigned char *p = (unsigned char *)recvbuf;

        ushort len = *(p+4) | *(p+5)<<4;

        if(len != recvFlag-6)   //recv error
        {

            qDebug() << "len != recvFlag-6"<< len << recvFlag;
            recvFlag = 0;
            return;
        }

        QString srcIP = QString("%1.%2.%3.%4").arg((uint)(*p)).arg((uint)(*(p+1))).arg((uint)(*(p+2))).arg((uint)(*(p+3)));
        ui->lineEdit_srcIP->setText(srcIP);


        if(ui->checkBox_hex_recv->isChecked())
        {
            QString str ;

            for(int i=0; i<len; i++)
            {

                str += QString("%1 ").arg(QString::number((uint)(*(p+6+i)), 16));



            }

            ui->textEdit_recv->append(str);
            ui->textEdit_recv->insertPlainText(tr("\r\n"));
        }
        else
        {

            ui->textEdit_recv->append(tr(recvbuf+6));

            ui->textEdit_recv->insertPlainText(tr("\r\n"));
        }
    }

    recvFlag = 0;

}


void SerialForm::handleSerialError(QSerialPort::SerialPortError err)
{
    if(err == QSerialPort::ResourceError)
    {
        QMessageBox::critical(this, tr("Error"), "串口连接中断");
        pserialport->close();
    }
}

void SerialForm::on_checkBox_broadcast_stateChanged(int arg1)
{
    if(ui->checkBox_broadcast->isChecked())
    {
        // ui->lineEdit_dstIP->setFocusPolicy(Qt::NoFocus);
        ui->lineEdit_dstIP->setEnabled(false);
    }
    else
    {
        ui->lineEdit_dstIP->setEnabled(true);
    }
}
